package tr.com.netgis;

import tr.com.netgis.Preferences.PrefSetLocationChangedApi;
import tr.com.netgis.util.Constants;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

/**
 * 
 * @author NetGis
 *
 */
public class NGApplication extends Application {

	private static Context context;
	private static PrefSetLocationChangedApi changedApi;

	public void onCreate() {
		super.onCreate();
		NGApplication.context = getApplicationContext();
		init();
	}

	public static Context getAppContext() {
		return NGApplication.context;
	}

	@Override
	public void onTerminate() {
		unbindService(changedApi.getServiceConnection());
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.unregisterOnSharedPreferenceChangeListener(changedApi.getPrefListener());
		NGApplication.getAppContext().unbindService(changedApi.getServiceConnection());
		nm.cancel(R.string.service_notif);
		super.onTerminate();
	}

	public static void assignPreferencesActivityToChangedApi (Preferences activity){
		if (changedApi == null)
			return;
		changedApi.setActivity(activity);
	}
	
	private void init () {
		
		changedApi = new PrefSetLocationChangedApi();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(changedApi.getPrefListener());
		NGApplication.getAppContext().bindService(Constants.MTS_SERVICE_INTENT, changedApi.getServiceConnection(), 0);
        
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	}
	
	static NotificationManager nm;

	
	public static void showNotification(String message, String messageTicket) {
        Notification notification = new Notification(R.drawable.ic_notif, messageTicket, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(getAppContext(), messageTicket.hashCode(), null, 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(getAppContext(), Constants.APP_NAME, message, contentIntent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_INSISTENT;
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_notif, notification);
    }
	
}
